#!/bin/bash

if [[ !$# -eq 1 ]]; then
    echo "Invalid param!"
    exit
fi

config_data=$(cat $1)
parse_cfg() {
    echo $config_data | python -c "import json; import sys;\
        obj=json.load(sys.stdin); print(obj$*)"
}

ssh=$(which ssh)
cmd_option="-o ExitOnForwardFailure=yes -NC -R"
remote_addr=$(parse_cfg "['remote']['addr']")
remote_bind_port=$(parse_cfg "['remote']['port']")
local_addr=$(parse_cfg "['local']['addr']")
local_bind_port=$(parse_cfg "['local']['port']")


if [ ! -d $log_path ]; then
    echo "mkdir: $log_path"
    mkdir -p $log_path
fi

echo "===="
echo "Command: $ssh"
echo "Remote address: $remote_addr, bind port: $remote_bind_port"
echo "Local address: $local_addr, bind port: $local_bind_port"

cmd="$ssh $cmd_option $remote_bind_port:$local_addr:$local_bind_port $remote_addr"

while [[ 1 ]]; do
    echo "$(date -Is) Run cmd: $cmd"
    $cmd
    echo "Lost connection, waiting for reconnect..."
    sleep 10
done
echo "Quit."

